package com.pfzy.rxbus2demo

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import com.blankj.rxbus.RxBus
import androidx.appcompat.app.AppCompatActivity

/**
 * 粘性测试
 */
class StickyTestActivity : AppCompatActivity() {
    private var tvSticky: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sticky_test)
        tvSticky = findViewById(R.id.tv_sticky)

        // 注册 String 类型事件
        RxBus.getDefault().subscribeSticky(this, object : RxBus.Callback<String>() {
            override fun onEvent(s: String) {
                tvSticky?.text = Config.appendMsg("sticky without $s")
            }
        })

        // 注册带 tag 为 "my tag" 的 String 类型事件
        RxBus.getDefault().subscribeSticky(this, "my tag", object : RxBus.Callback<String>() {
            override fun onEvent(s: String) {
                tvSticky?.text = Config.appendMsg("sticky with $s")
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        RxBus.getDefault().unregister(this)
    }

    fun postWithoutTag(view: View?) {
        Config.restoreMsg()
        RxBus.getDefault().post("tag")
    }

    fun postWithTag(view: View?) {
        Config.restoreMsg()
        RxBus.getDefault().post("tag", "my tag")
    }

    companion object {
        fun start(context: Context) {
            val starter = Intent(context, StickyTestActivity::class.java)
            context.startActivity(starter)
        }
    }
}
